const userinfo = require("../database/userinfo");
const verify = require("../modules/verify");

module.exports = async (req, res)=>{
  const {token, nickName="", birth, email="", team=""} = req.body;

  if(!token){
    res.send({
      code:0,
      msg:"缺少必传参数：token",
      data:null
    })
    return;
  }

  try{
    const tokenData = await verify(token);

    const obj = {};
    // 根据接收到的参数，决定要更新数据库中的哪些字段
    if(nickName) obj.nickName = nickName;
    if(email) obj.email = email;
    if(birth) obj.birth = new Date(birth).getTime();
    if(team) obj.team = team;
    await userinfo.updateOne({ userId: tokenData.id }, obj);
    res.send({
      code:1,
      msg:"修改个人信息成功",
      data:null
    })
  }catch(err){
    if(err.name === "JsonWebTokenError"){
      res.send({
        code: 3,
        msg: "登录失效或未登录",
        data: null
      })
    }else{
      res.send({
        code: 2,
        msg: "数据库出错",
        data: err.toString()
      })
    }
  }
}
